
#include "Motion.h"
#include "Magic.h"
#include "Creature.h"

int Motions = 0;

void Motion::move(Missile *m)
{
    real_move(m);
    m->OnStep();
}

void Motion::real_move(Missile *m)
{
    Rect &r = m->getPosition();
    r.x += r.w;
    r.y += r.h;
}

MoveToPoint::MoveToPoint(const Rect &dest) : m_dest(dest)
{
}

void MoveToPoint::setDest(const Rect &dest)
{
    m_dest = dest;
}

void MoveToPoint::real_move(Missile *m)
{
    Rect &r = m->getPosition();
    double speed = (double)r.w;
    double d = r.distance(m_dest);
    if (d <= speed)
    {
        r = m_dest;
        m->OnHitPlace();
    }
    else
    {
        r.x += (short)(speed * (m_dest.x - r.x) / d);
        r.y += (short)(speed * (m_dest.y - r.y) / d);
    }
}

TraceMonster::TraceMonster(Monster *m) : m_monster(m)
{
    if (m_monster)
        m_monster->used();
}

TraceMonster::~TraceMonster()
{
    if (m_monster)
        m_monster->unused();
}

void TraceMonster::setTarget(Monster *m)
{
    if (m_monster)
        m_monster->unused();
    m_monster = m;
    if (m_monster)
        m_monster->used();
}

void TraceMonster::real_move(Missile *m)
{
    if (!m_monster)
        return;

    Rect &mr = m_monster->getPosition();
    Rect &r = m->getPosition();
    double speed = (double)r.w;
    double d = r.distance(mr);
    if (d <= speed)
    {
        r = mr;
        m->OnHitMonster();
    }
    else
    {
        r.x += (short)(speed * (mr.x - r.x) / d);
        r.y += (short)(speed * (mr.y - r.y) / d);
    }
};
